package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.jcp.xml.dsig.internal.SignerOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 常用Controller
 * */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;


    /**
     * 文件上传
     * */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 使用uuid重新生成文件名,防止文件名重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        // 创建文件
        File dir = new File(basePath);
        // 检测是否存在目录
        if (!dir.exists()) {
            boolean isCreated = dir.mkdirs();
            if (!isCreated) {
                // 处理目录创建失败的情况
                System.err.println("Failed to create directory: " + basePath);
                // 可以抛出异常或者返回错误响应
                throw new IOException("Failed to create directory: " + basePath);
            }
        }
        try {
            file.transferTo(new File(basePath + fileName));
            return R.success(fileName);
        } catch (IOException e) {
            log.error("Failed to upload file: {}", fileName, e);
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * */
    @GetMapping("/download")
    public R<String> download(String name, HttpServletResponse response) {
        // 输入流 这条语句创建了一个 FileInputStream 对象，并在 try 语句的括号中声明。当 try 块结束时，无论是否发生异常，inputStream 都会被自动关闭。
        try (FileInputStream fileInputStream = new FileInputStream(new File(basePath + name))) {
            // 输出流
            ServletOutputStream outputStream = response.getOutputStream();
            // 设置响应头
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            fileInputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            log.error("File not found: {}", basePath + name, e);
        } catch (IOException e) {
            log.error("I/O error occurred while processing the file: {}", basePath + name, e);
        }
        // 输出流
        return R.success(name);
    }
}
